class Gist < ActiveRecord::Base
    include ModelHelper
    
    after_save :apply_tags

    has_many :tags, :through => :gists_tags
    has_many :gists_tags

    belongs_to :user
    belongs_to :citation

    validates_presence_of :title
    validates_presence_of :result
    validates_presence_of :citation_id
    validates_presence_of :user_id
    validates_presence_of :tag_list

    validates_length_of :title, :maximum => 255
    validates_length_of :result, :maximum => 1024

    # 'tags is a virtual attribute
    def tag_list
        @tag_list || @tag_list = self.tags.collect{|tag| tag.name + ' '}
    end

    def tag_list=(tag_list)
        @tag_list = tag_list
    end

    private

    def apply_tags
        GistsTag.delete_all(["gist_id = ?", self.id]) # clear current tags
        tag_names = @tag_list.split(' ')
        tag_names.each do |tag_name|
            tag = Tag.find_or_create_by_name(:name => tag_name)
            self.tags << tag
        end
    end

    ##########################################################
    # Finds tags applied to gists
    def self.get_tags(options = {})
        sql = "SELECT id, name, count FROM ("
        sql << "SELECT tags.id, tags.name, COUNT(tags.id) as count "
        sql << "FROM tags "
        sql << "INNER JOIN gists_tags ON tags.id = gists_tags.tag_id "
        sql << "GROUP BY tags.id, tags.name "
        add_limit!(sql,options)
        sql << ") AS t ORDER BY LOWER(t.name)"
        Tag.find_by_sql(sql)
    end

    #############################################################
    # Gets gists that have been tagged with the specified tags
    def self.get_tagged(tags = nil, options = {:limit => 20})

        sql = "SELECT * "
        sql << "FROM gists "
        sql << "INNER JOIN gists_tags ON gists_tags.gist_id = gists.id "
        sql << "INNER JOIN tags ON gists_tags.tag_id = tags.id "
        sql << "WHERE " + make_and_sql_where("tags.name", tags) if tags
        #sql << "GROUP BY feeds.id, feeds.title, feeds.description, feeds.display_uri, feeds.uri "
        sql << "ORDER BY gists.id DESC"
        add_limit!(sql,options)

        self.find_by_sql(sql)
    end
end
